<?php
require_once('../inc/connect.php');
$section = 'User';
session_start();

$user = $_SESSION['email'];

$error;
if($user)
{
    if(isset($_POST['submit']))
    {
        $oldpass = md5($_POST['oldpass']);
        $newpass = md5($_POST['newpass']);
        $renewpass = md5($_POST['renewpass']);
        
        $conn = mysql_connect(DB_HOST, DB_USER, DB_PASS)
            or die();
        mysql_select_db(DB_NAME)
            or die();
        
        $q = mysql_query("SELECT password FROM users WHERE email='$user'")
            or die("Malformed query!");
        
        $row = mysql_fetch_assoc($q);
        $oldpassdb = $row['password'];
        
        if($oldpass == $oldpassdb)
        {
            if($newpass == $renewpass)
            {
                $qc = mysql_query("UPDATE users SET password='$newpass' WHERE email='$user'")
                    or die("Malformed query!");
                
                session_destroy();
            }
            else
                $error = "New passwords don't match!";
        }
        else
            $error = "Old password doesn't match!";
    }
}
else
    $error = "Must be logged in to change passsord!";

?>
<!DOCTYPE html>

<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Change Password</title>
    <link rel="stylesheet" type="text/css" href="../css/reset.css" />
    <link rel="stylesheet" type="text/css" href="../css/style.css" />
  </head>
  
  <body>
<?php include('../inc/nav.php') ;?>
<?php include('../inc/header.php') ;?>
    <div id="content">
<?php if(isset($error)): ?>
      <p><?php echo $error; ?></p>
      <p><a href="changepassword.php">Return</a></p>
<?php else: if(isset($_POST['submit'])): ?>
      <p>Password has been changed!</p>
      <p><a href="index.php">Return to index.</a></p>
<?php else: ?>
      <form action="changepassword.php" method="POST">
        <table>
          <tbody>
            <tr>
              <td>Old password:</td>
              <td><input type="password" name="oldpass"/></td>
            </tr>
            <tr>
              <td>New password:</td>
              <td><input type="password" name="newpass"/></td>
            </tr>
            <tr>
              <td>Repeat new password:</td>
              <td><input type="password" name="renewpass"/></td>
            </tr>
          </tbody>
          <tfoot>
            <tr>
              <td colspan="2">
                <input type="submit" name="submit" value="Change password" />
              </td>
            </tr>
          </tfoot>
        </table>
      </form>
<?php endif; endif; ?>
    </div><!-- #content -->
<?php include('../inc/footer.php') ;?>
  </body>
</html>
